<template>
  <div class="app-container">
    <!-- 搜索表单框 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px">
      <el-form-item label="护理等级名称" prop="levelName">
        <el-input
          v-model="queryParams.levelName"
          placeholder="请输入护理等级名称"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          style="width: 240px">
          <el-option
            v-for="dict in sys_nurse_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 新增护理等级按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="24" style="text-align: right">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:level:add']"
          >新增护理等级</el-button
        >
      </el-col>
    </el-row>

    <!-- 使用表格展示列表查询数据 -->
    <el-table v-loading="loading" :data="levelList">
      <!-- 注意这里prop=levelName是从后端查询到的数据属性 -->
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="护理等级名称" align="center" prop="levelName" />
      <el-table-column label="执行护理计划" align="center" prop="planName" />
      <el-table-column label="护理费用(元/月)" align="center" prop="careFee" />
      <el-table-column label="等级说明" align="center" prop="description">
        <template #default="scope">
          <el-tooltip
            :content="scope.row.description"
            placement="top"
            :show-after="200">
            <span class="description-text">{{ scope.row.description }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_nurse_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="danger"
            :disabled="scope.row.disable"
            @click="handleDelete(scope.row)"
            v-hasPermi="['service:level:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            :disabled="scope.row.disable"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['service:level:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            @click="handleStop(scope.row)"
            v-hasPermi="['service:level:stop']"
            >{{ scope.row.status == 0 ? "启用" : "禁用" }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改护理等级对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form
        ref="levelRef"
        :model="form"
        :rules="rules"
        label-width="150px"
        label-position="left">
        <el-form-item label="护理等级名称" prop="levelName">
          <el-input
            v-model="form.levelName"
            placeholder="请输入护理等级名称"
            maxlength="10"
            show-word-limit />
        </el-form-item>
        <el-form-item label="护理费用(元/月)" prop="careFee">
          <el-input
            v-model="form.careFee"
            placeholder="请输入护理费用(元/月)"
            type="number"
            min="0"
            step="0.01" />
          <!-- 限制小数位置两位 step -->
        </el-form-item>
        <!-- 添加护理计划下拉框 -->
        <el-form-item label="护理计划" prop="carePlanId">
          <el-select
            v-model="form.carePlanId"
            placeholder="请选择执行护理计划"
            filterable
            clearable>
            <el-option
              v-for="plan in carePlanList"
              :key="plan.id"
              :label="plan.name"
              :value="plan.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_nurse_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="等级说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Level">
//导入对应的api接口
import {
  listLevel,
  getLevel,
  delLevel,
  addLevel,
  updateLevel,
  stopLevel,
  getCarePlanList,
  getElderBindIdList,
} from "@/api/service/level";

const { proxy } = getCurrentInstance();
const { sys_nurse_status } = proxy.useDict("sys_nurse_status");

//查询到的列表数据
const levelList = ref([]);
//开启关闭对话框
const open = ref(false);
//el-table中页面加载时显示加载组件
const loading = ref(true);
//显示隐藏el-form表单标签
const showSearch = ref(true);
//总的记录数
const total = ref(0);
//新增修改编辑框的标题
const title = ref("");
//查询所有护理计划
const carePlanList = ref([]);
//获取绑定老人的护理等级id
const elderBindIds = ref([]);
//添加编辑 删除按钮置灰属性
const disable = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    levelName: null,
    status: null,
  },
  rules: {
    levelName: [
      { required: true, message: "护理等级名称不能为空", trigger: "blur" },
    ],
    carePlanId: [
      { required: true, message: "执行护理计划不能为空", trigger: "blur" },
    ],
    careFee: [
      { required: true, message: "护理费用(元/月)不能为空", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效的数字，最多两位小数",
        trigger: "blur",
      },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    description: [
      { required: true, message: "等级说明不能为空", trigger: "blur" },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);

/** 查询护理等级列表 */
function getList() {
  loading.value = true;

  // 同时调用两个API，确保数据都获取完成后再处理
  Promise.all([listLevel(queryParams.value), getElderBindIdList()])
    .then(([levelResponse, elderBindResponse]) => {
      // 设置基础数据
      levelList.value = levelResponse.rows;
      total.value = levelResponse.total;
      elderBindIds.value = elderBindResponse.data;

      // 遍历levelList 为数组每一项添加disable属性
      levelList.value.forEach((item) => {
        // 判断当前护理等级项的id是否存在elderBindIds中
        // 存在disable为true，不存在disable为false
        // 处理item.id可能是字符串的情况，转换为数字进行比较
        const itemId = parseInt(item.id);
        if (elderBindIds.value.includes(itemId)) {
          item.disable = true;
        } else {
          item.disable = false;
        }
      });

      loading.value = false;
    })
    .catch((error) => {
      console.error("获取数据失败:", error);
      loading.value = false;
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  //即使新增编辑表框上次输入的数据清空了
  //form中的数据还在，需要手动清空
  form.value = {
    id: null,
    levelName: null,
    carePlanId: null,
    careFee: null,
    status: null,
    description: null,
    createdAt: null,
    createdBy: null,
    updatedAt: null,
    updatedBy: null,
    remark: null,
    extend1: null,
    extend2: null,
  };
  //调用element-plus组件库的重置表单方法，
  // 重置新增编辑对话框中的表单验证规则
  proxy.resetForm("levelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作，点击提交按钮，提交数据 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加护理等级";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getLevel(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改护理等级";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["levelRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateLevel(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLevel(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除护理等级编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delLevel(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/**启用 停用 */
function handleStop(row) {
  const _id = row.id;
  proxy.$modal
    .confirm(
      "是否确认" +
        (row.status == 0 ? "启用" : "停用") +
        '护理等级编号为"' +
        _id +
        '"的数据项？'
    )
    .then(function () {
      return stopLevel(_id, row.status == 0 ? 1 : 0);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

getList();

//查询所有护理计划
const carePlanQueryParams = reactive({
  pageNum: 1,
  pageSize: 1000,
  name: null,
  status: null,
});
getCarePlanList(carePlanQueryParams.value).then((response) => {
  carePlanList.value = response.rows;
});
</script>

<style scoped>
.description-text {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
